<?php namespace App\Admin\Base;

//基础条件
use App\Core\Repository\Criterias\FixedCriteria;
use App\Core\Repository\Criterias\SortCriteria;

use Auth, Route, Input, Request;
use App\Admin\Access\Operation\Repository as OperationRepository;
use App\Admin\Access\OperationLog\Repository as OperationLogRepository;

trait LogService {
    
    public $withOpLog = true;
    public $opLogData = [];
	
    //获取操作日志
    public function getOpLogs(){
        $id = Input::get('id', '');
        if(!is_numeric($id)){
            return $this->inputError();
        }
        $repository = new OperationLogRepository();
        $repository->addCriterias([
            new FixedCriteria('controller', $this->getControllerName()),
            new FixedCriteria('data_id', $id),
            new SortCriteria('time', 'DESC')
        ]);
        $repository->getQuery()->join('sys_user', 'sys_user.user_id', '=', 'sys_operation_log.user_id');
        $repository->getQuery()->selectRaw('sys_operation_log.id, sys_operation_log.op_name, sys_operation_log.time, sys_user.username, sys_user.nickname');
        $data = $repository->all();
        return $this->success(['data' => $data]);
    }
    
    //记录日志
	protected function opLog(){
        if(!Request::isMethod('post')){
            return ;
        }
        $input = $this->toJson(Input::all());
		$user = Auth::user();
		$operation = $this->getCurrentOperation();
		if(!$operation){
			return false;
		}
        $this->fillOpLogData($operation);
        $repository = new OperationLogRepository();
        $controllerRaw = preg_replace('/@.*/', '', $operation->code);
        $controller = str_replace('App\\Http\\Controllers\\', '', $controllerRaw);
        try {
            foreach($this->opLogData as $item){
                $repository->create([
                    'operation_id' => $operation->id,
                    'op_name' => $operation->name,
                    'controller' => $controller,
                    'user_id' => $user->user_id,
                    'time' => time(),
                    'ip' => Input::ip(),
                    'input' => $input,
                    'data_id' => $item['id'],
                    'data_name' => $item['name'],
                    'data' => $item['data']
                ]);
            }
		} catch (\Exception $ex) {
            
		}
        
	}
    
    //填充数据
    private function fillOpLogData($operation){
        $logConfig = $operation->log_config ? json_decode($operation->log_config, true) : [];
        if(!$logConfig || !isset($logConfig['data_source']) || !$logConfig['data_source']){
            return $this;
        }
        $dataSource = $logConfig['data_source'];
        $idName = $logConfig['data_id'];
        $nameName = $logConfig['data_name'];
        switch ($dataSource) {
            case '0' : //自定义
                foreach($this->opLogData as $key => $item){
                    if(!isset($item['id'])){
                        unset($this->opLogData[$key]);
                        continue;
                    }
                    if(!isset($item['name'])){
                        $this->opLogData[$key]['name'] = '';
                    }
                    if(!isset($item['data'])){
                        $this->opLogData[$key]['data'] = '';
                    }
                }
                break;
            case '1' : //单条输入
                $id = Input::get($idName, '');
                $name = $nameName ? Input::get($nameName, '') : '';
                $this->opLogData[] = [
                    'id' => $id,
                    'name' => $name,
                    'data' => ''
                ];
                break;
            case '2' : //批量输入
                $idsStr = Input::get($nameName, '');
                $ids = explode(',', $idsStr);
                foreach($ids as $id){
                    $this->opLogData[] = [
                        'id' => $id,
                        'name' => '',
                        'data' => ''
                    ];
                }
                break;
            case '3' : //创建模型
                if($this->createModel){
                    $this->opLogData[] = [
                        'id' => $this->createModel->{$idName},
                        'name' => $this->createModel->{$nameName},
                        'data' => $this->createModel->toJson()
                    ];
                }
                break;
            case '4' : //编辑模型
                if($this->updateModel){
                    $this->opLogData[] = [
                        'id' => $this->updateModel->{$idName},
                        'name' => $this->updateModel->{$nameName},
                        'data' => $this->updateModel->toJson()
                    ];
                }
                break;
            case '5' : //修改模型
                foreach($this->changeModels as $model){
                    $this->opLogData[] = [
                        'id' => $model->{$idName},
                        'name' => $model->{$nameName},
                        'data' => $model->toJson()
                    ];
                }
                break;
            case '6' : //删除模型
                foreach($this->deleteModels as $model){
                    $this->opLogData[] = [
                        'id' => $model->{$idName},
                        'name' => $model->{$nameName},
                        'data' => $model->toJson()
                    ];
                }
                break;
        }
        return $this;
	}

    //获取当前操作
    private function getCurrentOperation(){
        $action = str_replace('App\\Http\\Controllers\\', '', Route::currentRouteAction());
        $operationRepository = new OperationRepository();
            $operation = $operationRepository->addCriteria(new FixedCriteria('code', $action))->first();
            if(!$operation){
                return false;
            }
            return $operation;
	}
    
    private function getControllerName(){
        return str_replace('App\\Http\\Controllers\\', '', get_class($this));
    }
}